import React, { useEffect, useState } from 'react';
import { Modal, Button, message, Typography, Spin, Empty } from 'antd';
import request from '@/utils/request';
import dayjs from 'dayjs';
import DraggableTable from '@/components/DraggableTable';
import type { TableProps } from 'antd/es/table';

const { Title, Text } = Typography;

const statusMap: Record<number, string> = {
  1: '发布成功',
  0: '发布失败',
  2: '待发布',
  3: '发布中'
};
const statusColor: Record<number, string> = {
  1: 'green',
  0: 'red',
  2: 'orange',
  3: 'blue'
};

interface ReleaseDetailModalProps {
  open: boolean;
  onCancel: () => void;
  releaseTaskId: string | null;
}

const ReleaseDetailModal: React.FC<ReleaseDetailModalProps> = ({
  open,
  onCancel,
  releaseTaskId
}) => {
  const [loading, setLoading] = useState(false);
  const [info, setInfo] = useState<any>(null);
  const [files, setFiles] = useState<any[]>([]);
  const [bpLoading, setBpLoading] = useState(false);
  const [columns, setColumns] = useState<TableProps<any>['columns']>([
    { title: '序号', dataIndex: 'index', key: 'index', width: 60, render: (_: any, __: any, idx: number) => idx + 1 },
    { title: '文件名', dataIndex: 'file_name', key: 'file_name', width: 200, ellipsis: true },
    { title: '文件路径', dataIndex: 'file_path', key: 'file_path', width: 200, ellipsis: true },
    { title: '数据大小(MB)', dataIndex: 'data_size', key: 'data_size', width: 120, render: (v: number) => (v / 1024 / 1024).toFixed(2) },
    { title: '任务型号', dataIndex: 'task_type', key: 'task_type', width: 100 },
    { title: '接收站', dataIndex: 'station', key: 'station', width: 100 },
    { title: '载荷', dataIndex: 'dm_zhname', key: 'dm_zhname', width: 100 },
    { title: '版本号', dataIndex: 'version_num', key: 'version_num', width: 100 },
    { title: '数据等级', dataIndex: 'data_level', key: 'data_level', width: 100 },
    { title: '数据发布时间', dataIndex: 'release_time', key: 'release_time', width: 160 },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (v: number) => <span style={{ color: statusColor[v] }}>{statusMap[v] || '-'}</span>
    },
    { title: '失败原因', dataIndex: 'error_message', key: 'error_message', width: 120 }
  ]);

  // 获取详情数据
  const fetchDetail = async () => {
    if (!releaseTaskId) return;
    setLoading(true);
    try {
      const res = await request.get('/Management/DataListReleaseDetail', {
        params: { release_task_id: releaseTaskId }
      });
      if (res.status === 200 && res.data.data) {
        setInfo(res.data.data.introduce);
        setFiles(res.data.data.files || []);
      }
    } catch (e: any) {
      message.error(e?.message || '获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open && releaseTaskId) {
      fetchDetail();
    }
    // 关闭时清空数据
    if (!open) {
      setInfo(null);
      setFiles([]);
    }
  }, [open, releaseTaskId]);

  // 断点续推
  const handleBreakpoint = async () => {
    setBpLoading(true);
    try {
      const res = await request.post('/Management/DataReleaseBreakpointContinuation', {
        release_task_ids: [releaseTaskId]
      });
      if (res.status === 200) {
        message.success('断点续推已发起');
        // 刷新数据
        fetchDetail();
      } else {
        message.error(res.data?.msg || '断点续推失败');
      }
    } catch (e: any) {
      message.error(e?.message || '断点续推失败');
    } finally {
      setBpLoading(false);
    }
  };

  return (
    <Modal
      title="发布报告详情"
      open={open}
      onCancel={onCancel}
      width={1200}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>
      ]}
      bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
    >
      <div style={{ padding: '0 24px' }}>
        <div style={{ textAlign: 'right', padding: '8px 0', fontSize: 14, color: '#666' }}>
          生成时间：{info?.generation_time ? dayjs(info.generation_time).format('YYYY-MM-DD HH:mm:ss') : '-'}
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : (
          <>
            {/* 汇总信息 */}
            <div style={{ background: '#f5f5f5', padding: 16, marginBottom: 24, borderRadius: 4 }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', marginBottom: 8 }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <Text strong>报告编号：</Text>
                  <Text>{info?.report_no || '-'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'center' }}>
                  <Text strong>发布开始时间：</Text>
                  <Text>{info?.release_start_time || '-'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'right' }}>
                  <Text strong>发布结束时间：</Text>
                  <Text>{info?.release_end_time || '-'}</Text>
                </div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', marginBottom: 8 }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <Text strong>发布数据总量(MB)：</Text>
                  <Text>{info?.files_size ? (info.files_size / 1024 / 1024).toFixed(2) : '-'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'center' }}>
                  <Text strong>成功数据量(MB)：</Text>
                  <Text>{info?.release_success_size ? (info.release_success_size / 1024 / 1024).toFixed(2) : '-'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'right' }}>
                  <Text strong>失败数据量(MB)：</Text>
                  <Text>{info?.release_fail_size ? (info.release_fail_size / 1024 / 1024).toFixed(2) : '-'}</Text>
                </div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <Text strong>文件数：</Text>
                  <Text>{info?.files_count || '-'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'center' }}>
                  <Text strong>成功文件数：</Text>
                  <Text>{info?.release_success_count || '0'}</Text>
                </div>
                <div style={{ flex: 1, minWidth: 200, textAlign: 'right' }}>
                  <Text strong>失败文件数：</Text>
                  <Text>{info?.release_fail_count || '0'}</Text>
                </div>
              </div>
            </div>

            {/* 文件明细表格 */}
            <div style={{ marginBottom: 8 }}>
              <Text strong>
                共{files.length}条数据，成功{info?.release_success_count || 0}条，失败{info?.release_fail_count || 0}条
              </Text>
            </div>

            {files.length > 0 ? (
              <DraggableTable
                rowKey="id"
                tableLayout="fixed"
                columns={columns}
                dataSource={files}
                size="small"
                bordered
                pagination={false}
                scroll={{ x: 'max-content', y: 350 }}
                onColumnsChange={(columns) => {
                  setColumns(columns);
                }}
              />
            ) : (
              <Empty description="暂无文件数据" style={{ margin: '40px 0' }} />
            )}

            {/* 断点续推按钮 */}
            {info?.release_fail_count > 0 && (
              <div style={{ marginTop: 16 }}>
                <Button type="primary" loading={bpLoading} onClick={handleBreakpoint}>
                  断点续推
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </Modal>
  );
};

export default ReleaseDetailModal;